//
//  CommunityDetailViewController.m
//  PTravel
//
//  Created by dllo on 15/11/23.
//  Copyright © 2015年 李涵. All rights reserved.
//

#import "CommunityDetailViewController.h"

@interface CommunityDetailViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (retain, nonatomic)UITableView *myTableView;
@property (retain, nonatomic)NSMutableArray *typesArr;
@property (retain, nonatomic)NSMutableArray *entryArr;
@property (retain, nonatomic)UIView *aView;
@property (retain, nonatomic)NSString *url;
@property (retain, nonatomic)DetailHead *detailH;
@property (assign, nonatomic)NSInteger num;
@property (retain, nonatomic)MBProgressHUD *hub;
@property (assign, nonatomic)BOOL isUp;
@end

@implementation CommunityDetailViewController

- (void)dealloc
{
    [_myTableView release];
    [_typesArr release];
    [_entryArr release];
    [_aView release];
    [_url release];
    [_detailH release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    //夜间模式判断
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColor:) name:@"night" object:nil];
    
}

- (void)changeColor:(NSNotificationCenter *)notification
{
    
    self.myTableView.backgroundColor = [Night cellColor];
    self.navigationController.navigationBar.barTintColor = [Night barColor];
    [self.myTableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.num = 0;
    self.nextPage = 1;
    self.isUp = NO;
    self.entryArr = [NSMutableArray array];
    self.url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/bbs/forum_thread_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&delcache=1&forum_id=%ld&forum_type=new&lat=38.88254517633509&lon=121.5397738930633&page=1&track_app_channel=App%%2520Store&track_app_version=6.8.2&track_device_info=iPhone7%%2C2&track_deviceid=94E2CF74-5FF7-49B9-8D69-620BF45F65A9&track_os=ios%%25209.1&v=1", (long)self.forum_id];
    
    self.myTableView = [[UITableView alloc] initWithFrame:BOUNDS style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.view addSubview:self.myTableView];
    [_myTableView release];
    [self.myTableView registerClass:[CommunityDetailTableViewCell class] forCellReuseIdentifier:@"CommunityDetailTableViewCell"];
    [self.myTableView registerClass:[StrategyTableViewCell class] forCellReuseIdentifier:@"StrategyTableViewCell"];
    [self.myTableView registerClass:[CommpanyTableViewCell class] forCellReuseIdentifier:@"CommpanyTableViewCell"];
    [self.myTableView registerClass:[CommpanyCell class] forCellReuseIdentifier:@"CommpanyCell"];
    [self.myTableView registerClass:[AnswerTableViewCell class] forCellReuseIdentifier:@"AnswerTableViewCell"];
    self.myTableView.backgroundColor = CELLCOLOR;
    [self getPic];
    self.navigationItem.title = self.name;
    [_myTableView release];
    
    self.aView = [[UIView alloc] initWithFrame:CGRectMake(BOUNDS.size.width/20-2, 26, 40, 2)];
    self.aView.backgroundColor = [UIColor greenColor];
    self.typesArr = [NSMutableArray array];
    [self getData:self.nextPage];
    [_aView release];
    [self addFooter];
    // 取消渲染
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    
    //    __unsafe_unretained typeof(self) vc = self;
    //__unsafe_unretained ViewController *vc = self;
    __unsafe_unretained CommunityDetailViewController *vc = self;
    // 添加上拉刷新尾部控件
    [self.myTableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        self.isUp = YES;
        vc.nextPage ++;
        [vc getData:vc.nextPage];
        
    }];
    
}

//tableview数据请求
- (void)getData:(NSInteger)nextPage
{
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.hub show:YES];
    self.hub.labelText = @"Waiting···";
    switch (self.num) {
        case 0:
            self.url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/bbs/forum_thread_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&delcache=1&forum_id=%ld&forum_type=new&lat=38.88254517633509&lon=121.5397738930633&page=%ld&track_app_channel=App%%2520Store&track_app_version=6.8.2&track_device_info=iPhone7%%2C2&track_deviceid=94E2CF74-5FF7-49B9-8D69-620BF45F65A9&track_os=ios%%25209.1&v=1", (long)self.forum_id, (long)self.nextPage];
            break;
        case 1:
            self.url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/bbs/forum_thread_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&delcache=1&forum_id=%ld&forum_type=1%%2C2%%2C6&lat=38.88254517633509&lon=121.5397738930633&page=%ld&track_app_channel=App%%2520Store&track_app_version=6.8.2&track_device_info=iPhone7%%2C2&track_deviceid=94E2CF74-5FF7-49B9-8D69-620BF45F65A9&track_os=ios%%25209.1&v=1", (long)self.forum_id, (long)self.nextPage];
            break;
        case 2:
            self.url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/company/together_list_by_fid?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&fid=%ld&lat=38.88254517633509&lon=121.5397738930633&page=%ld&track_app_channel=App%%2520Store&track_app_version=6.8.2&track_device_info=iPhone7%%2C2&track_deviceid=94E2CF74-5FF7-49B9-8D69-620BF45F65A9&track_os=ios%%25209.1&v=1", (long)self.forum_id, (long)self.nextPage];
            break;
        case 3:
            self.url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/ask/question/list_by_fid?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&fid=%ld&lat=38.88254517633509&lon=121.5397738930633&page=%ld&track_app_channel=App%%2520Store&track_app_version=6.8.2&track_device_info=iPhone7%%2C2&track_deviceid=94E2CF74-5FF7-49B9-8D69-620BF45F65A9&track_os=ios%%25209.1&v=1", (long)self.forum_id, (long)self.nextPage];
            break;
        case 4:
            self.url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/bbs/forum_thread_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&delcache=1&forum_id=%ld&forum_type=4&lat=38.88254517633509&lon=121.5397738930633&page=%ld&track_app_channel=App%%2520Store&track_app_version=6.8.2&track_device_info=iPhone7%%2C2&track_deviceid=94E2CF74-5FF7-49B9-8D69-620BF45F65A9&track_os=ios%%25209.1&v=1", (long)self.forum_id, (long)self.nextPage];

            break;
        default:
            break;
    }
    
    NSLog(@"isUp%d", self.isUp);
    [AppTools getAFN:self.url block:^(id result) {
        if (self.isUp == NO) {
            [self.entryArr removeAllObjects];
        }
        NSMutableDictionary *bigDic = result;
        if (self.num == 0 || self.num == 1 || self.num == 4) {
            id small = [bigDic objectForKey:@"data"];
            if ([small isKindOfClass:[NSMutableArray class]]) {
                for (NSMutableDictionary *dic in small) {
                    Theme *theme = [[Theme alloc] init];
                    [theme setValuesForKeysWithDictionary:dic];
                    [self.entryArr addObject:theme];
                }
            }else{
                
                NSMutableArray *enArr = [small objectForKey:@"entry"];
                for (NSMutableDictionary *dic in enArr) {
                    Theme *theme = [[Theme alloc] init];
                    [theme setValuesForKeysWithDictionary:dic];
                    [self.entryArr addObject:theme];
                }
            }
            
        }else if(self.num == 3){
            id small = [bigDic objectForKey:@"data"];
            if ([small isKindOfClass:[NSMutableArray class]]) {
                for (NSMutableDictionary *dic in small) {
                    Answer *answer = [[Answer alloc] init];
                    [answer setValuesForKeysWithDictionary:dic];
                    [self.entryArr addObject:answer];

                }
            }else{
                
                NSMutableArray *enArr = [small objectForKey:@"entry"];
                for (NSMutableDictionary *dic in enArr) {
                    Answer *answer = [[Answer alloc] init];
                    [answer setValuesForKeysWithDictionary:dic];
                    [self.entryArr addObject:answer];

                }
            }
           
        }else{
            id small = [bigDic objectForKey:@"data"];
            if ([small isKindOfClass:[NSMutableArray class]]) {
                for (NSMutableDictionary *dic in small) {
                    Commpany *strategy = [[Commpany alloc] init];
                    [strategy setValuesForKeysWithDictionary:dic];
                    [self.entryArr addObject:strategy];
                }
            }else{
                
                NSMutableArray *enArr = [small objectForKey:@"entry"];
                for (NSMutableDictionary *dic in enArr) {
                    Commpany *strategy = [[Commpany alloc] init];
                    [strategy setValuesForKeysWithDictionary:dic];
                    [self.entryArr addObject:strategy];
                    
                }
            }

        }
        [self.myTableView reloadData];
        [self.myTableView footerEndRefreshing];
        self.hub.hidden = YES;
        self.isUp = NO;
    }];
    
}

#pragma mark === 头像数据请求
- (void)getPic
{
        [AppTools getAFN:self.url block:^(id result) {
        NSMutableDictionary *bigDic = result;
        NSMutableDictionary *smallDic = [bigDic objectForKey:@"data"];
        self.detailH = [[DetailHead alloc] initWithFrame:CGRectMake(0, 0, BOUNDS.size.width, 200)];
        NSURL *url = [NSURL URLWithString:[smallDic objectForKey:@"photo"]];
        [self.detailH.bgImage sd_setImageWithURL:url placeholderImage:IMAGE];
        [self.detailH.image sd_setImageWithURL:url placeholderImage:IMAGE];
        //毛玻璃效果
        [self.detailH.bgImage setImageToBlur:self.detailH.bgImage.image blurRadius:kLBBlurredImageDefaultBlurRadius completionBlock:^{
            
            
        }];
        self.myTableView.tableHeaderView = self.detailH;
    }];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.entryArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.num == 0) {
        CommunityDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommunityDetailTableViewCell" forIndexPath:indexPath];
        cell.theme = [self.entryArr objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = CELLCOLOR;
        return  cell;
    }else if(self.num == 1 || self.num == 4){
        StrategyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StrategyTableViewCell" forIndexPath:indexPath];
        cell.theme = [self.entryArr objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = CELLCOLOR;
        return cell;
    }else if(self.num == 3){
        AnswerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AnswerTableViewCell" forIndexPath:indexPath];
        cell.aanswer = [self.entryArr objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = CELLCOLOR;
        return cell;
    }else{
        CommpanyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommpanyCell" forIndexPath:indexPath];
        cell.commpany = [self.entryArr objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = CELLCOLOR;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.num == 0) {
        return 120;
    }else if(self.num == 3){
        return 120;
    }else{
        
        return 80;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"asd";
}

#pragma mark === 表头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSMutableArray *typesArr = [NSMutableArray arrayWithObjects:@"最新", @"攻略", @"结伴", @"问答", @"转让", nil];
    UIView *headV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BOUNDS.size.width, 0)];
    headV.backgroundColor = [UIColor whiteColor];
    for (int i = 0; i < 5; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(BOUNDS.size.width/5*i, 5, BOUNDS.size.width/5, 20);
        [button setTitle:typesArr[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithWhite:0.500 alpha:1.000] forState:UIControlStateNormal];
        switch (i) {
            case 0:
                [button addTarget:self action:@selector(newAction) forControlEvents:UIControlEventTouchUpInside];
                break;
            case 1:
                [button addTarget:self action:@selector(strategyAction) forControlEvents:UIControlEventTouchUpInside];
                break;
            case 2:
                [button addTarget:self action:@selector(commpanyAction) forControlEvents:UIControlEventTouchUpInside];
                break;
            case 3:
                [button addTarget:self action:@selector(aqAction) forControlEvents:UIControlEventTouchUpInside];
                break;
            case 4:
                [button addTarget:self action:@selector(transferAction) forControlEvents:UIControlEventTouchUpInside];
                break;
            default:
                break;
        }
        [button setTitleColor:TEXTCOLOR forState:UIControlStateNormal];
        button.backgroundColor = CELLCOLOR;
        [headV addSubview:button];
    }
    UIView *bView = [[UIView alloc] initWithFrame:CGRectMake(0, 27.5, BOUNDS.size.width, 0.4)];
    bView.backgroundColor = CELLCOLOR;
    headV.backgroundColor = CELLCOLOR;
    [headV addSubview:bView];
    [headV addSubview:self.aView];
    return headV;
}
#pragma mark === 点击转换
//最新
- (void)newAction
{
    NSLog(@"最新");
    [UIView animateWithDuration:0.2 animations:^{
        
        
        self.aView.frame = CGRectMake(BOUNDS.size.width/20-2, 26, 40, 2);
    }];
    
    self.num = 0;
    [self getData:self.nextPage];
}
//攻略
- (void)strategyAction
{
    NSLog(@"攻略");
    
    [UIView animateWithDuration:0.2 animations:^{
        
        
        self.aView.frame = CGRectMake(BOUNDS.size.width/20-2+BOUNDS.size.width/5, 26, 40, 2);
    }];
    self.num = 1;
    [self getData:self.nextPage];
}
//结伴
- (void)commpanyAction
{
    NSLog(@"结伴");
    
    [UIView animateWithDuration:0.2 animations:^{
        
        
        self.aView.frame = CGRectMake(BOUNDS.size.width/20-2+BOUNDS.size.width/5*2, 26, 40, 2);
    }];
    self.num = 2;
    [self getData:self.nextPage];
}
//问答
- (void)aqAction
{
    NSLog(@"问答");
    
    [UIView animateWithDuration:0.2 animations:^{
        
        
        self.aView.frame = CGRectMake(BOUNDS.size.width/20-2+BOUNDS.size.width/5*3, 26, 40, 2);
    }];
    self.num = 3;
    [self getData:self.nextPage];
}
//转让
- (void)transferAction
{
    NSLog(@"转让");
    [UIView animateWithDuration:0.2 animations:^{
        
        
        self.aView.frame = CGRectMake(BOUNDS.size.width/20-2+BOUNDS.size.width/5*4, 26, 40, 2);
    }];
    self.num = 4;
    [self getData:self.nextPage];
}

#pragma mark === 下拉变大
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //刚开始y的偏移量初始值就是-264
//    NSLog(@"y1 === %f",scrollView.contentOffset.y);
    CGFloat y = scrollView.contentOffset.y + 64;//加上导航栏高度,第一次是-200
//    NSLog(@"y2 === %f",y);
    
    if (y < 0) {
        CGRect frame = self.detailH.bgImage.frame;
        frame.origin.y = y;//偏移了多少,
        frame.size.height = 200 -y;//tablview向下偏移了多少,高度就是多少
        self.detailH.bgImage.frame = frame;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
